package org.joinme.backend.service;

import org.joinme.backend.mapper.ApplicationRecordMapper;
import org.joinme.backend.mapper.ApplicationRecordMapper;
import org.joinme.backend.model.ApplicationCarPoolingRecord;
import org.joinme.backend.model.ApplicationRecord;
import org.joinme.backend.model.CarPoolingRecord;
import org.joinme.backend.model.ParticipateRecord;
import org.joinme.backend.util.ConstUtil;
import org.joinme.backend.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ApplicationService {
    @Autowired
    ApplicationRecordMapper applicationRecordMapper;

    @Autowired
    private ParticipateService participateService;

    @Autowired
    private CarPoolingService carPoolingService;

    //添加拼单记录
    public int addApplicationRecord(ApplicationRecord record){
        record.setApplicationTime(DateUtil.getCurrentTime());
        record.setApplicationStatus(ConstUtil.APPLICATION_CHECKING);

        return applicationRecordMapper.insertSelective(record);
    }

    //查询用户的申请记录
    public List<ApplicationCarPoolingRecord> getApplicationList(int userId, int start, int limit){
        return applicationRecordMapper.selectByUserId(userId, start * limit, limit);
    }

    //计算用户申请总数
    public int countApplicationList(int userId){
        return applicationRecordMapper.countByUserId(userId);
    }

    //更新申请状态
    public boolean updateApplicationRecord(ApplicationRecord record){
        boolean result = false;
        if(applicationRecordMapper.updateByPrimaryKeySelective(record) > 0){
            result = true;
            //如果更新成功而且更新状态为通过，要更新对应的拼单
            if(record.getApplicationStatus() == ConstUtil.APPLICATION_ALLOWED){
                //添加参与角色为0的参与记录
                ParticipateRecord participateRecord = new ParticipateRecord();
                participateRecord.setCarPoolingId(record.getCarPoolingId());
                participateRecord.setUserId(record.getUserId());
                participateRecord.setParticipateTime(DateUtil.getCurrentTime());
                participateRecord.setParticipateRole(ConstUtil.ROLE_PARTICIPANT);
                participateRecord.setParticipateStatus(ConstUtil.PARTICIPATE_ING);

                boolean b1 = participateService.addParticipateRecord(participateRecord);

                //更新拼单信息
                CarPoolingRecord carPoolingRecord = carPoolingService.getCarPoolingRecord(record.getCarPoolingId());
                int currentNum = carPoolingRecord.getCurrentNum();
                carPoolingRecord.setCurrentNum(currentNum + 1);

                boolean b2 = carPoolingService.updateCarPoolingRecord(carPoolingRecord);

                result = b1 && b2;
            }
        }
        return result;
    }
}
